package com.y2020.d0102;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @author 歪大哥😁
 * @date 2020-01-02.
 */
public class CyclicBarrierStudy {

    public static void main(String[] args) throws InterruptedException {

        CyclicBarrier cyclicBarrier = new CyclicBarrier(3);

        new Thread(() -> {
            String name = Thread.currentThread().getName();
            for (int i = 0; i < 10; i++) {
                System.out.println("开始等待-" + name + " 第-" + i);
                try {
                    cyclicBarrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
                System.out.println("巨龙苏醒-" + name + " 第-" + i);
            }
        }).start();

        new Thread(() -> {
            String name = Thread.currentThread().getName();
            for (int i = 0; i < 10; i++) {
                System.out.println("开始等待-" + name + " 第-" + i);
                try {
                    cyclicBarrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
                System.out.println("巨龙苏醒-" + name + " 第-" + i);
            }
        }).start();

        new Thread(() -> {
            String name = Thread.currentThread().getName();
            for (int i = 0; i < 10; i++) {
                System.out.println("一秒后开始等待-" + name + " 第-" + i);
                try {
                    Thread.sleep(1000L);
                    cyclicBarrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
                System.out.println("巨龙苏醒-" + name + " 第-" + i);
            }
        }).start();

        Thread.sleep(20000L);
    }

}
